import datetime
import logging

from django.db.models.signals import post_save, post_init, post_delete
from django.dispatch import receiver

from finance.api.utils import create_journal, get_account, remove_journal
from purchase.models import WareHouseEntry, PurchasePayOrder, PurchasePayOrderDetail

logger = logging.getLogger("django")


# 初始化
@receiver(post_init, sender=WareHouseEntry)
def receipt_init(instance, **kwargs):
    instance.old_imprest = instance.imprest


@receiver(post_save, sender=WareHouseEntry)
def handle_pay_order(sender, instance, created, **kwargs):
    """生产采购付款单"""
    logger.info('handle_pay_order')

    order_data = {
        "account": instance.account,
        "pay_time": instance.warehouse_time,
        "supplier": instance.supplier,
        "user": instance.buyer,
        "payable": instance.total_amount,
        "pay_amount": instance.imp_amount,
        "discount_amount": 0,
        "actual_amount": instance.imp_amount,
        "oper": instance.oper_user,
        "entry_code": instance.code,
        "flag": 1 if instance.flag == 0 else 2,
    }
    logger.info(order_data)
    if created and instance.imprest:
        inst = PurchasePayOrder(**order_data)
        inst.save()
        item = PurchasePayOrderDetail(pay_order=inst, entry=instance, pay_amount=instance.imp_amount)
        item.save()
    elif not created:
        if instance.old_imprest and instance.imprest:
            PurchasePayOrder.objects.filter(entry_code=instance.code).update(**order_data)
            item = PurchasePayOrderDetail.objects.filter(entry_id=instance.id, pay_order__entry_code=instance.code).first()
            item.pay_amount = instance.imp_amount
            item.save(update_fields=['pay_amount'])
        else:
            if instance.old_imprest:
                PurchasePayOrder.objects.filter(entry_code=instance.code).delete()
            elif instance.imprest:
                inst = PurchasePayOrder(**order_data)
                inst.save()
                item = PurchasePayOrderDetail(pay_order=inst, entry=instance, pay_amount=instance.imp_amount)
                item.save()

    account = get_account(instance.account_id)

    if instance.flag in [0, 1]:
        if instance.imprest:
            data = {
                'order_no': instance.code,
                'customer': instance.supplier or None,
                'order_time': datetime.datetime.now(),
                'account': instance.account or None,
                'source': '采购订单直接付款' if instance.flag == 0 else '采购退货直接收款',
                'money': instance.imp_amount * -1 if instance.flag == 0 else abs(instance.imp_amount),
                'balance': account.balance,
                'user': instance.oper_user or None,
                'desc': instance.remark,
                'created': created,
            }
            logger.info(data)
            # 流水账记录
            create_journal(**data)
        elif instance.old_imprest and not instance.imprest:
            remove_journal(instance.code)


@receiver(post_delete, sender=WareHouseEntry)
def handle_pay_order_del(sender, instance, **kwargs):
    """删除支付订单"""
    if instance.imprest:
        PurchasePayOrder.objects.filter(entry_code=instance.code).delete()
        remove_journal(instance.code)


@receiver(post_save, sender=PurchasePayOrder)
def handle_journal(sender, instance, created, **kwargs):
    """流水账"""
    logger.info('handle_journal')

    account = get_account(instance.account_id)

    if instance.flag == 0:
        data = {
            'order_no': instance.code,
            'customer': instance.supplier or None,
            'order_time': datetime.datetime.now(),
            'account': instance.account or None,
            'source': '采购订单/退货',
            'money': instance.actual_amount * -1,
            'balance': account.balance,
            'user': instance.oper or None,
            'desc': instance.remark,
            'created': created,
        }
        logger.info(data)
        # print(data)
        # 流水账记录
        create_journal(**data)


@receiver(post_delete, sender=PurchasePayOrder)
def handle_remove_journal(sender, instance, **kwargs):
    """删除支付订单"""
    remove_journal(instance.code)


